package com.sdap2.service.impl;

import com.sdap2.common.exception.BusinessException;
import com.sdap2.dao.DeviceDAO;
import com.sdap2.dao.SoilDataDAO;
import com.sdap2.dto.SoilDataStatsDTO;
import com.sdap2.entity.Device;
import com.sdap2.entity.SoilData;
import com.sdap2.service.DeviceService;
import com.sdap2.service.SoilDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SoilDataServiceImpl implements SoilDataService {
    
    private final DeviceDAO deviceDAO;
    private final SoilDataDAO soilDataDAO;
    private final DeviceService deviceService;
    
    @Override
    @Transactional(readOnly = true)
    public List<SoilData> getDataStats(String serialNumber, String token) {
        // 检查设备是否存在
        Device device = deviceDAO.findBySerialNumber(serialNumber)
                .orElseThrow(() -> new BusinessException("设备不存在"));
                
        // 检查权限
        if (!deviceService.checkDeviceOwnership(device.getId(), token)) {
            throw new BusinessException("无权操作此设备");
        }
        
        // 获取所有数据记录
        return soilDataDAO.findAllByDeviceId(device.getId());
    }
    
    @Override
    @Transactional
    public SoilData save(SoilData soilData) {
        return soilDataDAO.save(soilData);
    }
} 